﻿using Newtonsoft.Json;
using System;

namespace Framework
{
    public class JsonHelper
    {
        /// <summary>
        /// JSON数据对象
        /// </summary>
        /// <returns>JSON串</returns>
        public static string DataToStrJSON(object v_objJSON)
        {
            if (null != v_objJSON)
            {
                return JsonConvert.SerializeObject(v_objJSON);
            }
            return string.Empty;
        }

        /// <summary>
        /// 把JSON字符串还原为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="szJson">JSON字符串</param>
        /// <returns>对象实体</returns>
        public static T ParseFormJson<T>(string szJson)
        {
            if (string.IsNullOrEmpty(szJson))
                return default(T);
            return JsonConvert.DeserializeObject<T>(szJson);
        }

        /// <summary>
        /// 把JSON字符串还原为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="szJson">JSON字符串</param>
        /// <returns>对象实体</returns>
        public static object ParseFormJson(string szJson, Type type)
        {
            if (string.IsNullOrEmpty(szJson))
                return null;
            return JsonConvert.DeserializeObject(szJson, type);
        }
    }
}
